// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM加载完成，开始初始化注册页面');

    // 如果是注册页面，初始化注册页面特定功能
    if (document.querySelector('.auth-page')) {
        console.log('检测到注册页面，开始初始化');
        initRegisterPage();
    } else {
        console.log('未检测到注册页面');
    }
});

// 初始化注册页面功能
function initRegisterPage() {
    console.log('初始化注册页面');

    // 初始化角色选择
    initRoleSelection();

    // 初始化表单验证
    initRegisterFormValidation();

    // 清除旧的错误状态
    clearFormErrors();

    // 绑定表单提交事件
    bindRegisterFormSubmit();

    console.log('注册页面初始化完成');
}

// 初始化角色选择
function initRoleSelection() {
    console.log('初始化角色选择功能');

    const roleOptions = document.querySelectorAll('.role-option');
    const roleInput = document.getElementById('register-role');

    console.log('找到角色选项:', roleOptions.length);
    console.log('找到角色输入框:', roleInput);

    if (roleOptions.length === 0) {
        console.error('未找到角色选项元素');
        return;
    }

    if (!roleInput) {
        console.error('未找到角色输入框元素');
        return;
    }

    roleOptions.forEach((option) => {
        option.addEventListener('click', function() {
            console.log('点击角色选项:', this.getAttribute('data-role'));

            // 移除所有选项的选中状态
            roleOptions.forEach(opt => {
                opt.classList.remove('selected');
                console.log('移除选中状态:', opt.getAttribute('data-role'));
            });

            // 添加当前选项的选中状态
            this.classList.add('selected');
            console.log('添加选中状态:', this.getAttribute('data-role'));

            // 设置角色值
            const role = this.getAttribute('data-role');
            roleInput.value = role;
            console.log('设置角色值为:', role);
        });
    });

    // 默认选择学生角色
    if (roleOptions.length > 0 && !roleInput.value) {
        console.log('设置默认角色为学生');
        roleOptions[0].click();
    }

    console.log('角色选择功能初始化完成');
}

// 绑定注册表单提交事件
function bindRegisterFormSubmit() {
    const registerForm = document.getElementById('register-form');

    if (registerForm) {
        console.log('找到注册表单，绑定提交事件');

        registerForm.addEventListener('submit', function(e) {
            console.log('表单提交事件触发');

            // 先进行前端验证
            if (!validateRegisterForm()) {
                console.log('表单验证失败，阻止提交');
                e.preventDefault();
            } else {
                console.log('表单验证通过，允许提交');
            }
        });
    } else {
        console.error('未找到注册表单元素');
    }
}

// 初始化注册表单验证
function initRegisterFormValidation() {
    console.log('初始化注册表单验证');

    // 为注册表单添加实时验证
    const registerEmail = document.getElementById('register-email');
    const registerPassword = document.getElementById('register-password');
    const registerConfirmPassword = document.getElementById('register-confirm-password');

    if (registerEmail) {
        registerEmail.addEventListener('input', function() {
            validateEmailField(this, 'register-email-error');
        });
    } else {
        console.error('未找到邮箱输入框');
    }

    if (registerPassword) {
        registerPassword.addEventListener('input', function() {
            validatePasswordField(this, 'register-password-error');
        });
    } else {
        console.error('未找到密码输入框');
    }

    if (registerConfirmPassword) {
        registerConfirmPassword.addEventListener('input', function() {
            validateConfirmPasswordField(this, registerPassword, 'register-confirm-password-error');
        });
    } else {
        console.error('未找到确认密码输入框');
    }

    console.log('注册表单验证初始化完成');
}

// 验证注册表单
function validateRegisterForm() {
    console.log('开始验证注册表单');

    const emailInput = document.getElementById('register-email');
    const passwordInput = document.getElementById('register-password');
    const confirmPasswordInput = document.getElementById('register-confirm-password');
    const roleInput = document.getElementById('register-role');

    let isValid = true;

    // 验证邮箱
    const email = emailInput.value.trim();
    if (!email) {
        showFieldError(emailInput, 'register-email-error', '邮箱不能为空');
        isValid = false;
    } else if (!validateEmail(email)) {
        showFieldError(emailInput, 'register-email-error', '请输入有效的邮箱地址');
        isValid = false;
    } else {
        hideFieldError(emailInput, 'register-email-error');
    }

    // 验证密码
    const password = passwordInput.value;
    if (!password) {
        showFieldError(passwordInput, 'register-password-error', '密码不能为空');
        isValid = false;
    } else if (!validatePassword(password)) {
        showFieldError(passwordInput, 'register-password-error', '密码长度应为6-20位');
        isValid = false;
    } else {
        hideFieldError(passwordInput, 'register-password-error');
    }

    // 验证确认密码
    const confirmPassword = confirmPasswordInput.value;
    if (!confirmPassword) {
        showFieldError(confirmPasswordInput, 'register-confirm-password-error', '请确认密码');
        isValid = false;
    } else if (confirmPassword !== password) {
        showFieldError(confirmPasswordInput, 'register-confirm-password-error', '两次输入的密码不一致');
        isValid = false;
    } else {
        hideFieldError(confirmPasswordInput, 'register-confirm-password-error');
    }

    // 验证角色选择
    if (!roleInput.value) {
        alert('请选择您的身份（学生或教师）');
        isValid = false;
    } else {
        console.log('角色选择验证通过:', roleInput.value);
    }

    console.log('表单验证结果:', isValid ? '通过' : '失败');
    return isValid;
}

// 验证邮箱字段
function validateEmailField(inputElement, errorElementId) {
    const email = inputElement.value.trim();
    if (!email) {
        showFieldError(inputElement, errorElementId, '邮箱不能为空');
    } else if (!validateEmail(email)) {
        showFieldError(inputElement, errorElementId, '请输入有效的邮箱地址');
    } else {
        hideFieldError(inputElement, errorElementId);
    }
}

// 验证密码字段
function validatePasswordField(inputElement, errorElementId) {
    const password = inputElement.value;
    if (!password) {
        showFieldError(inputElement, errorElementId, '密码不能为空');
    } else if (!validatePassword(password)) {
        showFieldError(inputElement, errorElementId, '密码长度应为6-20位');
    } else {
        hideFieldError(inputElement, errorElementId);
    }
}

// 验证确认密码字段
function validateConfirmPasswordField(confirmInput, passwordInput, errorElementId) {
    const confirmPassword = confirmInput.value;
    const password = passwordInput.value;

    if (!confirmPassword) {
        showFieldError(confirmInput, errorElementId, '请确认密码');
    } else if (confirmPassword !== password) {
        showFieldError(confirmInput, errorElementId, '两次输入的密码不一致');
    } else {
        hideFieldError(confirmInput, errorElementId);
    }
}

// 验证邮箱格式
function validateEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

// 验证密码长度
function validatePassword(password) {
    return password.length >= 6 && password.length <= 20;
}

// 显示字段错误
function showFieldError(inputElement, errorElementId, message) {
    const errorElement = document.getElementById(errorElementId);
    if (!errorElement) {
        console.error('未找到错误元素:', errorElementId);
        return;
    }

    const formGroup = inputElement.parentNode.parentNode;
    formGroup.classList.add('has-error');
    errorElement.textContent = message;
    errorElement.style.display = 'block';
    errorElement.style.opacity = '1';

    console.log('显示错误:', message);
}

// 隐藏字段错误
function hideFieldError(inputElement, errorElementId) {
    const errorElement = document.getElementById(errorElementId);
    if (!errorElement) return;

    const formGroup = inputElement.parentNode.parentNode;
    formGroup.classList.remove('has-error');
    errorElement.style.opacity = '0';
    setTimeout(() => {
        errorElement.style.display = 'none';
    }, 300);
}

// 清除表单错误状态
function clearFormErrors() {
    const errorMessages = document.querySelectorAll('.error-message');
    errorMessages.forEach(error => {
        error.style.display = 'none';
        error.style.opacity = '0';
    });

    const formGroups = document.querySelectorAll('.form-group');
    formGroups.forEach(group => {
        group.classList.remove('has-error');
    });

    console.log('清除表单错误状态');
}